package com.web.handler;

import com.web.domain.Dict;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author xukk
 * @date 2017/6/2
 */
@Slf4j
public class KdUsernamePasswordAuthenticationFilter  extends UsernamePasswordAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(KdUsernamePasswordAuthenticationFilter.class);
    private boolean postOnly = true;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String code=request.getParameter("code");
        String type = request.getParameter("login_type");
        String remember_account=request.getParameter("remember_account");
        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        if (StringUtils.isBlank(type) ) {
            type = "1";
        }
        if(code!=null)
            code=code.trim();
        username = username.trim();

        password=password.trim();

        if(type.equals("2")){
            if(StringUtils.isBlank(code))
                code="";
            Cookie[] cookies= request.getCookies();
            String value="";
            if(cookies!=null&&cookies.length>0){
                for(Cookie cookie:cookies){
                    if(cookie.getName().equals("captchaCode")){
                        value=cookie.getValue();
                        break;
                    }
                }
               String captachValue="";
                if(!code.equalsIgnoreCase(captachValue)){
                    throw new AuthenticationServiceException("验证码错误" );
                }
                else {
                    try {
                    } catch (Exception e) {
                            logger.warn("删除登录验证码:"+Dict.Constants.REDIS_NAMESPACE_KAPACHA+value+" 失败");
                    }
                }
            }

        }

        username = username.trim();
        if(remember_account!=null&&remember_account.equals("on")){
            Cookie cookie=new Cookie("remember_account",username);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*7);
            response.addCookie(cookie);
        }

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        this.setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }


}
